package com.kob.botruningsystem.service.impl.utils;

import com.kob.botruningsystem.utils.BotInterface;
import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.function.Supplier;

@Component
public class Consumer extends Thread{
    private Bot bot;
    private static RestTemplate restTemplate;
    private final static String receiveBotMoveUrl = "http://127.0.0.1:3030/pk/receive/bot/move/";


    @Autowired
    public void setRestTemplate(RestTemplate restTemplate){
        Consumer.restTemplate = restTemplate;
    }
    public void startTimeout(long timeout,Bot bot){
        this.bot = bot;
        this.start();//调用当前的run函数(新线程)

        try {
            this.join(timeout);//最多等待timeout秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            this.interrupt();//中断当前线程
        }

    }
    private String addUid(String code){
        int k = code.indexOf(" implements java.util.function.Supplier<Integer>");
        return code.substring(0,k) + bot.getBotId().toString() +code.substring(k);

    }
    @Override
    public void run() {
        Supplier<Integer> botInterface = Reflect.compile(
                "com.kob.botruningsystem.utils.Bot" + bot.getBotId().toString(),
                addUid(bot.getBotCode())
        ).create().get();

        File file = new File("input.txt");
        try (PrintWriter fout = new PrintWriter(file)){
            fout.println(bot.getInput());
            fout.flush();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        Integer direction = botInterface.get();

//        System.out.println("move-direction: "+bot.getBotId()+ " "+ direction);
        MultiValueMap<String,String> data = new LinkedMultiValueMap<>();
        data.add("user_id",bot.getUserId().toString());
        data.add("direction",direction.toString());
        restTemplate.postForObject(receiveBotMoveUrl,data,String.class);
    }
}
